package system

import (
	"errors"
	"fmt"
	"time"

	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	systemReq "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
	systemRes "github.com/flipped-aurora/gin-vue-admin/server/model/system/response"
	"gorm.io/gorm"
)

type OrderService struct{}

// CreateOrder 创建订单
func (orderService *OrderService) CreateOrder(order system.SysOrder) (err error) {
	// 生成订单号
	if order.OrderNum == "" {
		order.OrderNum = fmt.Sprintf("ORD%d", time.Now().Unix())
	}
	// 设置下单时间
	if order.CreatedAt == 0 {
		order.CreatedAt = time.Now().Unix()
	}
	err = global.GVA_DB.Create(&order).Error
	return err
}

// DeleteOrder 删除订单
func (orderService *OrderService) DeleteOrder(order system.SysOrder) (err error) {
	err = global.GVA_DB.Delete(&order).Error
	return err
}

// UpdateOrder 更新订单
func (orderService *OrderService) UpdateOrder(order system.SysOrder) (err error) {
	// 更新时间
	order.UpdatedAt = time.Now().Unix()
	err = global.GVA_DB.Save(&order).Error
	return err
}

// GetOrderById 根据ID获取订单
func (orderService *OrderService) GetOrderById(id uint) (order system.SysOrder, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&order).Error
	return
}

// GetOrderInfoList 分页获取订单列表
func (orderService *OrderService) GetOrderInfoList(req systemReq.SearchOrderParams) (orderList []systemRes.SystemOrderListPageResponseItem, total int64, err error) {
	limit := req.PageSize
	offset := req.PageSize * (req.Page - 1)
	db := global.GVA_DB.Model(&system.SysOrder{}).
		Select("md_order.*, md_user.nickname,md_order.desc as product_name").
		Joins("left join md_user on md_user.uuid = md_order.user_uuid").
		Where("md_order.order_type = 1")

	// 条件查询
	if req.OrderNo != nil {
		db = db.Where("order_no LIKE ?", "%"+*req.OrderNo+"%")
	}
	// 商品名称模糊查询
	if req.ProductName != nil {
		db = db.Where("desc LIKE ?", "%"+*req.ProductName+"%")
	}
	// 订单状态精准查询
	if req.OrderStatus != nil {
		db = db.Where("order_status = ?", *req.OrderStatus)
	}
	// 下单用户模糊查询
	// 日期范围查询
	if req.StartDate != "" {
		db = db.Where("created_at >= ?", req.StartDate)
	}
	if req.EndDate != "" {
		db = db.Where("created_at <= ?", req.EndDate)
	}

	err = db.Count(&total).Error
	if err != nil {
		return
	}

	// 排序
	db = db.Order("id desc")

	err = db.Limit(limit).Offset(offset).Find(&orderList).Error
	return orderList, total, err
}

// GetAllOrders 获取所有订单
func (orderService *OrderService) GetAllOrders() (orders []system.SysOrder, err error) {
	err = global.GVA_DB.Find(&orders).Error
	return orders, err
}

// DeleteOrdersByIds 批量删除订单
func (orderService *OrderService) DeleteOrdersByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]system.SysOrder{}, "id in ?", ids.Ids).Error
	return err
}

// GetOrderGroups 获取订单分组
func (orderService *OrderService) GetOrderGroups() (groups []string, orderGroupMap map[string]int64, err error) {
	type result struct {
		OrderGroup string `json:"order_group"`
		Count      int64  `json:"count"`
	}
	var results []result
	err = global.GVA_DB.Model(&system.SysOrder{}).Select("order_group, count(*) as count").Group("order_group").Find(&results).Error
	if err != nil {
		return
	}

	orderGroupMap = make(map[string]int64)
	for _, r := range results {
		if r.OrderGroup != "" {
			groups = append(groups, r.OrderGroup)
			orderGroupMap[r.OrderGroup] = r.Count
		}
	}
	return
}

// UpdateOrderStatus 更新订单状态
func (orderService *OrderService) UpdateOrderStatus(req systemReq.UpdateOrderStatusReq) (err error) {
	var order system.SysOrder
	err = global.GVA_DB.Where("id = ?", req.ID).First(&order).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("订单不存在")
		}
		return err
	}

	// 更新状态
	order.OrderStatus = req.Status
	// 如果状态是已发货(3)，设置发货日期
	if req.Status == 3 && order.SendAt == 0 {
		order.SendAt = time.Now().Unix()
	}

	err = global.GVA_DB.Save(&order).Error
	return err
}

// GetOrderStats 获取订单统计
func (orderService *OrderService) GetOrderStats() (stats systemRes.OrderStatsResponse, err error) {
	// 总订单数
	err = global.GVA_DB.Model(&system.SysOrder{}).Where("order_type = 1").Count(&stats.TotalOrders).Error
	if err != nil {
		return
	}

	// 各状态订单数 (1 待支付 2 制作中 3 已发货 4 已完成 5 已取消)
	global.GVA_DB.Model(&system.SysOrder{}).Where("order_type = 1 and order_status = ?", 1).Count(&stats.PendingOrders)
	global.GVA_DB.Model(&system.SysOrder{}).Where("order_type = 1 and order_status = ?", 2).Count(&stats.ConfirmedOrders)
	global.GVA_DB.Model(&system.SysOrder{}).Where("order_type = 1 and order_status = ?", 3).Count(&stats.ShippedOrders)
	global.GVA_DB.Model(&system.SysOrder{}).Where("order_type = 1 and order_status = ?", 4).Count(&stats.DeliveredOrders)
	global.GVA_DB.Model(&system.SysOrder{}).Where("order_type = 1 and order_status = ?", 5).Count(&stats.CancelledOrders)

	// 总金额
	type AmountResult struct {
		Total int64 `json:"total"`
	}
	var amountResult AmountResult
	global.GVA_DB.Model(&system.SysOrder{}).Where("order_type = 1").Select("COALESCE(SUM(price), 0) as total").Scan(&amountResult)
	stats.TotalAmount = float64(amountResult.Total)

	// 今日订单数和金额
	todayStart := time.Now().Truncate(24 * time.Hour).Unix()
	todayEnd := todayStart + 24*60*60 - 1
	global.GVA_DB.Model(&system.SysOrder{}).Where("order_type = 1 and created_at >= ? AND created_at <= ?", todayStart, todayEnd).Count(&stats.TodayOrders)
	global.GVA_DB.Model(&system.SysOrder{}).Where("order_type = 1 and created_at >= ? AND created_at <= ?", todayStart, todayEnd).Select("COALESCE(SUM(price), 0) as total").Scan(&amountResult)
	stats.TodayAmount = float64(amountResult.Total)

	return stats, nil
}

// GetOrderByOrderNo 根据订单号获取订单
func (orderService *OrderService) GetOrderByOrderNo(orderNo string) (order system.SysOrder, err error) {
	err = global.GVA_DB.Where("order_num = ?", orderNo).First(&order).Error
	return
}
